<script setup lang="ts">
import { onMounted, ref, computed, nextTick, watch } from 'vue'
import type { StyleValue } from 'vue'

const props = withDefaults(
  defineProps<{
    id: number
    size?: number
  }>(),
  {
    size: 50,
  },
)

const iconRef = ref<HTMLElement | null>(null)
const scaleValue = ref<number>(0.2)

const iconBoxStyle = computed<StyleValue>(() => ({
  width: `${props.size}px`,
  height: `${props.size}px`,
  display: 'inline-flex',
  justifyContent: 'center',
  alignItems: 'center',
  position: 'relative',
  overflow: 'hidden',
}))

const iconStyle = computed<StyleValue>(() => ({
  transform: `scale(${scaleValue.value})`,
  transformOrigin: 'center center',
  // 可以添加过渡效果
  transition: 'transform 0.2s ease',
  position: 'absolute',
}))

watch(
  () => props.size,
  () => {
    nextTick(() => {
      calculateScale()
    })
  },
)

onMounted(() => {
  nextTick(() => {
    calculateScale()
  })
})

function calculateScale() {
  if (iconRef.value) {
    const computedStyle = window.getComputedStyle(iconRef.value)
    const originalWidth = parseFloat(computedStyle.width) || 1 // 防止除零
    const originalHeight = parseFloat(computedStyle.height) || 1

    // 避免除零和无效值
    if (originalWidth > 0 && originalHeight > 0) {
      const scale = Math.min(props.size / originalWidth, props.size / originalHeight)
      scaleValue.value = scale
    }
  }
}
</script>

<template>
  <div :style="iconBoxStyle">
    <div ref="iconRef" :class="['icon-chef', `chef_${props.id}`]" :style="iconStyle"></div>
  </div>
</template>

<style lang="scss" scoped></style>
